package com.czeczek.integration;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.Assert;

public class MoveProcessedFiles implements Tasklet, InitializingBean {
    private Resource directory;

    public RepeatStatus execute(StepContribution contribution, 
                                ChunkContext chunkContext) throws Exception {
    	String fileToMove = (String)chunkContext.getStepContext().getJobParameters().get("input.file");
        File dir = directory.getFile();
    
        Resource resource = new UrlResource(fileToMove);
        
        try {
        	FileUtils.copyFileToDirectory(resource.getFile(), dir, true);
        	FileUtils.deleteQuietly(resource.getFile());
        	
        } catch(IOException ex) {
            throw new UnexpectedJobExecutionException("Could not move file " + 
            		resource.getFile().getAbsolutePath() + " to "+dir.getAbsolutePath()+". Reason="+ex.getMessage());        	
        }
        return RepeatStatus.FINISHED;
    }

    public void setProcessedDirectoryResource(Resource directory) {
        this.directory = directory;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(directory, "directory must be set");
    }

}
